package com.example.springbootcache.controller;

import com.example.springbootcache.mapper.CityMapper;
import com.example.springbootcache.po.City;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class CityController {

    @Autowired
    private CityMapper cityMapper;


    @RequestMapping("/insert")
    @Cacheable(cacheNames = "baseCache", key = "#city.country")
    public City insert(@RequestBody City city) {
        cityMapper.insert(city);
        log.info("success :{}", city);
        return city;
    }

    @GetMapping("/getCity/{country}")
    @Cacheable(cacheNames = "baseCache", key = "#country")
    public City getCity(@PathVariable String country) {
        return cityMapper.findByName(country);
    }

    @GetMapping("/updateCache/{name}/{country}")
    @CachePut(cacheNames = "baseCache", key = "#city.country")
    public City updateCache(@RequestBody City city) {
        int result = cityMapper.updateCache(city);
        log.info("delete result: {}", result);
        return city;

    }

    @GetMapping("/clearCache/{country}")
    @CacheEvict(value = "baseCache", key = "#country")
    public void clearCache(@PathVariable String country) {
        int result = cityMapper.delete(country);
        log.info("delete result: {}", result);
    }
}
